package com.zzr.demo.redis.service.impl;

import com.zzr.demo.redis.service.LogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author: xiaomi
 * @date: 2021/10/7
 * @description: 将同一天的日志追加到同一个 key 中
 */
@Service
@Slf4j
public class SameDayLogServiceImpl implements LogService {

    final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
    final char SPLIT_LABEL = '\n';

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public void append(String str) {
        String key = generateKey();
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        Integer append = valueOperations.append(key, str + SPLIT_LABEL);
        log.info("key：{}.返回字节长度：{}", key, append);
    }

    @Override
    public String getLog(String key) {
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        String str = valueOperations.get(key);
        String[] split = str.split(SPLIT_LABEL + "");
        for (String s : split) {
            log.info(s);
        }
        return str;
    }

    @Override
    public String generateKey() {
        String date = LocalDateTime.now().format(formatter);
        return "log::" + date;
    }


}
